from django.contrib.auth.backends import ModelBackend
from django.conf import settings

import re
from .models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData


"""根据account查询用户：判断用户是用用户名还是手机号登陆"""
def get_user_by_account(account):

    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


"""自定义用户认证后段，实现多账号登陆"""
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_user_by_account(username)

        if user and user.check_password(password):
            return user


"""对当前传入的user生成激活邮箱url"""
def generate_verify_email_url(user):

    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600 * 24)

    data = {'user_id':user.id, 'email':user.email}
    data_sign = serializer.dumps(data).decode()

    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + data_sign

    return verify_url


"""传入token返回user"""
def check_token_to_user(token):

    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600 * 24)
    try:
        data = serializer.loads(token)
    except BadData:
        return None

    else:
        user_id = data.get('user_id')
        email = data.get('email')

        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user